<template>
  <div class="push-blank-wrap js-clickbody" @click="bodyClick('body')">
    <div class="chose-course-top">
      <div class="header-left">
        <span id="pushBack" class="back-arrow" @click="goList"></span>
        <a class="block-blank"></a>
      </div>
      <div class="course-title">
        {{ detail.level_title }}
      </div>
      <div class="btn-group">
        <div v-show="!isStart">
          <a @click="goReport" v-if="+detail.write_count !== 0">查看报告</a>
          <a @click="showNewWords">{{ showWords ? "隐藏生词" : "显示生词" }}</a>
          <a @click="goWordList">生词列表</a>
        </div>
        <div v-show="isStart">
          <div class="spend-time">
            <img src="~assets/reverse/time.png" alt="" />
            <span>{{ readTime | HHmmssFilter }}</span>
          </div>
        </div>
        <a @click="readPrint">打印</a>
      </div>
    </div>
    <div class="list-wrap">
      <div class="article-content-wrap two-colum-width">
        <div
          class="add-diff-wrods"
          @click="subNewsWords"
          v-show="isSelectWords"
        >
          <span>加入</span>
          <span>生词本</span>
        </div>
        <div class="article-content two-colum-width scrolToMinView">
          <p class="article-title">
            {{ this.detail.question_title }}
          </p>
          <div class="read-tip">
            <div>
              <img src="~assets/super-read/read-time.png" alt="" />
              <span>参考时长：</span>
              <span>{{ detail.read_time }}min</span>
            </div>
            <div>
              <img src="~assets/super-read/difficulty-icon.png" alt="" />
              <span>难度：</span>
              <div class="read-stars">
                <span
                  v-for="(star, index) in new Array(5).fill('star')"
                  :key="`${star}-${index}`"
                  :class="{
                    'read-star': +detail.read_difficulty_id >= index + 1,
                    'read-star-none': +detail.read_difficulty_id < index + 1,
                  }"
                ></span>
              </div>
            </div>
          </div>
          <p
            class="article-paragraph"
            v-for="(paragraph, index) in content"
            :key="`paragraph-p-${index}`"
          >
            <span v-for="(word, i) in paragraph" :key="word + i">
              <template v-if="isSelectWords">
                <template v-if="/###\d{0,}###/.test(word)">
                  <div
                    class="select-blank"
                  >
                    <strong
                      :data-id="word.replace(/[^0-9]/g, '')"
                      class="select-blank-num"
                    >{{word.replace(/[^0-9]/g, '')}}</strong>
                  </div>
                </template>
                <span
                  v-else
                  class="js_diff_word js_show_word"
                  @click="selectWords($event, word)"
                  >{{ word }}</span
                >
              </template>
              <template v-else>
                <template v-if="/###\d{0,}###/.test(word)">
                  <div
                    class="blank"
                    @click.stop="blankClick($event)"
                  >
                    <strong
                      :data-id="word.replace(/[^0-9]/g, '')"
                      class="blank-num"
                    >{{word.replace(/[^0-9]/g, '')}}</strong>
                    <strong class="blank-val"></strong>
                  </div>
                </template>
                <template
                  v-else-if="(/([A-Za-z]+['’]?[A-Za-z])/).test(word)">
                  <a-popover
                    transitionName=""
                    overlayClassName="lookup-popover"
                    placement="bottom"
                    :visible="visibleKey === `paragraphVisible${index}-${i}`"
                    :destroyTooltipOnHide="true"
                    trigger="click"
                  >
                    <!-- <template v-if="word.split(',').length > 1">
                        <span
                          class="pop-content-word"
                          :style="{
                            'padding-left': itemI === 1 ? 0 : '4px',
                            'padding-right': itemI === 0 ? 0 : '4px',
                          }"
                          v-for="(wordItem, itemI) in word.split(',')"
                          :key="wordItem + itemI"
                          @click="checkWord(wordItem, `paragraphVisible${index}-${i}`)"
                        >
                          {{ wordItem }}{{ itemI == 0 ? "," : "" }}
                        </span>
                    </template> -->
                    <span
                      :yxp_attr="viLock?'disable':''"
                      :id="`word-paragraphVisible${index}-${i}`"
                      class="pop-content-word js_show_word synclock"
                      @click="checkWord(word, `paragraphVisible${index}-${i}`)"
                      >{{ word }}</span
                    >
                    <div slot="content">
                      <div class="lookup-content">
                        <div class="title">
                          {{ translate.prototype_word || translate.select_word }}
                          <img
                            v-show="translate.prototype_word"
                            class="icon-img"
                            @click.stop="translateVoice"
                            src="~assets/reverse/audio-play1.png"
                            alt=""
                          />
                        </div>
                        <div class="translate">
                          {{ translate.translate || "未找到该生词" }}
                        </div>
                        <div class="btn-group">
                          <a
                            :disabled="!translate.prototype_word"
                            @click.stop="addWord"
                            ><img
                              class="icon-img"
                              src="~assets/reverse/add1.png"
                              alt=""
                            />添加生词</a
                          >
                          <a @click.stop="translateDetail"
                            ><img
                              class="icon-img"
                              src="~assets/reverse/detail1.png"
                              alt=""
                            />单词详解</a
                          >
                        </div>
                      </div>
                    </div>
                  </a-popover>
                </template>
                <template v-else>
                  {{word}}
                </template>
              </template>
            </span>
          </p>
        </div>
      </div>

      <div class="article-answer two-colum-width">
        <div class="answer-main">
          <div class="answer-toptip">
            温馨提示：优先阅读题干，做题效率更高哦！
          </div>
          <div class="answer-sub">
            <div class="answer-sub-section scrolToMinView" id="selectSection">
              <div v-for="(sub, subIndex) in subjects" :key="`sub${sub.id}`">
                <p class="sub-title">第{{ sub.id }}题</p>
                <div
                  class="sub-item js-scroll-el"
                  v-for="(opt, i) in sub.options"
                  :key="`labelopt${i}`"
                >
                  <label
                    :class="{ 'opt-radio__checked': +sub.answer === i }"
                    class="opt-radio"
                  >
                    <input
                      :disabled="!isStart"
                      v-model="sub.answer"
                      @click="radioClick(subIndex, opt)"
                      type="radio"
                      :value="i"
                      :name="`sub-${sub.id}`"
                    />
                    <template v-if="i === 0">A</template>
                    <template v-else-if="i === 1">B</template>
                    <template v-else-if="i === 2">C</template>
                    <template v-else-if="i === 3">D</template>
                  </label>
                  <div class="sub-options-item">
                    <template v-if="isSelectWords">
                      <span
                        class="js_diff_word js_show_word"
                        @click="selectWords($event, optWord)"
                        v-for="optWord in opt"
                        :key="`subq-${optWord}`"
                      >
                        {{ optWord }}
                      </span>
                    </template>
                    <template v-else>
                      <a-popover
                        transitionName=""
                        overlayClassName="lookup-popover"
                        placement="bottom"
                        :visible="visibleKey === `subWordVisible${subIndex}-${i}-${optIndex}`"
                        v-for="(optWord, optIndex) in opt"
                        :key="`checksubword-${optWord}-${optIndex}`"
                        :destroyTooltipOnHide="true"
                        trigger="click"
                      >
                        <span
                          :yxp_attr="viLock?'disable':''"
                          :id="`word-subWordVisible${subIndex}-${i}-${optIndex}`"
                          class="pop-content-word pop-split-word js_show_word synclock"
                          @click="checkWord(optWord, `subWordVisible${subIndex}-${i}-${optIndex}`)"
                          >{{ optWord }}</span
                        >
                        <div slot="content">
                          <div class="lookup-content">
                            <div class="title">
                              {{
                                translate.prototype_word ||
                                  translate.select_word
                              }}
                              <img
                                v-show="translate.prototype_word"
                                class="icon-img"
                                @click.stop="translateVoice"
                                src="~assets/reverse/audio-play1.png"
                                alt=""
                              />
                            </div>
                            <div class="translate">
                              {{ translate.translate || "未找到该生词" }}
                            </div>
                            <div class="btn-group">
                              <a
                                :disabled="!translate.prototype_word"
                                @click.stop="addWord"
                                ><img
                                  class="icon-img"
                                  src="~assets/reverse/add1.png"
                                  alt=""
                                />添加生词</a
                              >
                              <a @click.stop="translateDetail"
                                ><img
                                  class="icon-img"
                                  src="~assets/reverse/detail1.png"
                                  alt=""
                                />单词详解</a
                              >
                            </div>
                          </div>
                        </div>
                      </a-popover>
                    </template>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="answer-option" :class="{'answer-option-start': isStart}">
            <p v-show="isStart">
              <span
                class="answer-num"
                :class="{ 
                  'is-answer': +num.answer >= 0,
                  'answer-item__select': stuIndex === stuSelectIndex
                  }"
                v-for="(num, stuIndex) in subjects"
                @click="scrollTitleClick(stuIndex)"
                :key="`num-${num.id}`"
              >
                {{ num.id }}
              </span>
            </p>
            <a-button
              v-show="!isStart"
              @click="startClickHandle"
              class="sub-btn"
              type="primary"
              >开始做题</a-button
            >
            <a-button
              v-show="isStart"
              @click="subAnswer"
              class="sub-btn"
              type="primary"
              :disabled="!canSub || readTime < 60"
              >提交答案</a-button
            >
          </div>
        </div>
      </div>
    </div>
    <Timetips ref="timetips"></Timetips>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import { checkWord, addWord } from "@/services/reverse";
import Timetips from "@/components/Timetips";
import {
  fetchReadQuestion,
  addReadDiffWord,
  fetchReadWord,
  handUpQuestion,
  printData
} from "@/services/super-read";
import { SUCCESS_CODE } from "@/utils/const";
import { Popover, message } from "ant-design-vue";
import _ from 'lodash';
import $ from "jquery";
export default {
  name: "pushBlank",
  components: {
    APopover: Popover,
  Timetips
  },
  data() {
    return {
      audio: {},
      viLock: false,
      lastvi: "",
      visibles: {},
      visibleKey: "-1",
      detail: {},
      stuSelectIndex: '',
      subjects: [],
      showWords: false,
      content: [],
      canSub: false,
      scrollTimer: null,
      subTimer: null,
      readTime: 0,
      translate: {},
      isStart: false,
      isSelectWords: this.$route.query.select_words,
      diffWords: new Set(),
      isnew:1,
      parent_id:0,
      package_id:0,
      title:'',
      is_doubleminus:sessionStorage.getItem('doubleminus_type')
    };
  },
  computed: {
    ...mapState({
      readCourseInfo: (state) => state.readCourseInfo,
      userInfo: (state) => state.userInfo,
      readCurrent: (state) => state.readCurrent,
      readDetail: (state) => state.readDetail
    }),
  },
  watch: {
    subjects: {
      handler: function(val) {
        let answersL = val.filter((v) => v.answer >= 0).length;
        if (answersL === val.length) {
          this.canSub = true;
        }
      },
      deep: true,
    },
  },
  methods: {
    ...mapMutations(["setTranslateModal", "setReadBroadModal", "setReadDetail", "setReadReport"]),
    outPopClick(oi) {
      console.log('1213', oi)
      if (typeof oi == "object") {
        if (this.visibles[this.lastvi] == true) {
          let dom = document.getElementsByClassName("ant-popover-open")[0]
          dom ? dom.click() : ''
        }
      } else {
        for (let i in this.visibles) {
          if (typeof oi == "string" && oi == i) continue;
          this.visibles[i] = false;
        }
      }
    },
    bodyClick(e) {
      if (e === 'body') {
        this.visibleKey = "-1"
      }
      if (!window[`bs:event:scroll:close`]) {
        this.visibleKey = "-1"
      }
    },
    async initList() {
      let id = '',
          res = {},
          detail;
          if (this.readCurrent.id !== this.readDetail.id) {
            id = this.readCurrent.id
            try {
              this.$loading.show()
              res = await fetchReadQuestion({
                question_id: id,
              })
              if (res.code !== SUCCESS_CODE) {
                return
              } else {
                this.setReadDetail(_.cloneDeep(res.data))
                detail = res.data
              }
              this.$loading.hide()
            } catch {
              this.$loading.hide()
            }
          } else {
            detail = _.cloneDeep(this.readDetail)
          }
          this.detail = detail;
          let article_title = detail.question_content;
          let string = article_title.split(/\n/);
          this.content = string.map((v) => {
            return v.replace(/(###\d{0,}###)/g, " $1 ").split(" ").filter(v => !!v);
          });
          //
          this.subjects = detail.subjects.map((v) => {
            let subject = v.subject.replace(/([A-Za-z0-9]+['’]?[A-Za-z0-9]*)/gi, " $1 ").split(" ");
            let options = v.options.map((v) => {
              return v.split(" ");
            });
            return Object.assign(v, { subject, options });
          });
    },
    goWordList() {
      this.$router.push({
        path: "/super-read/beforeStudy",
        query: {
          ...this.$route.query,
          read: true,
        },
      });
    },
    readPrint() {
      printData({
        question_type: '6',
        question_id: this.$route.query.id,
        from: 'read_article'
      }).then(res => {
        if (res.code === SUCCESS_CODE) {
          this.$message.success("已提交打印,请到管理平台进行打印");
        } else {
          this.$message.error("您打印的过于频繁，请休息一下");
        }
      })
    },
    readMain() {
      this.setReadBroadModal({
        visible: true,
        mainidea: this.detail.mainidea,
      });
    },
    showNewWords() {
      let checkWords = $(".js_show_word");
      if (this.showWords) {
        this.showWords = false;
        // pop 组件会修改动态类名 这里更改 style
        checkWords.css({
          "background-color": "",
          color: "#333",
        });
      } else {
        fetchReadWord({
          question_id: this.readCurrent.id,
        }).then((res) => {
          if (res.code === SUCCESS_CODE) {
            if (!res.data.length) {
              this.$message.error('您还没有加入生词哦~')
              return
            }
            let selectWords = res.data.map((v) => v.select_word);
            checkWords.each((i, el) => {
              let text = this.replaceText($(el).text());
              if (selectWords.includes(text)) {
                $(el).css({
                  "background-color": "#27BFA3",
                  color: "#fff",
                });
              }
            });
            this.showWords = true;
          }
        });
      }
    },
    replaceText(word) {
      const pattern = /[^a-zA-Z']/g;
      return word.replace(pattern, "");
    },
    checkWord(value, i) {
      if (!value || this.viLock) return;
      this.viLock = true;
      checkWord({ word: value }).then((res) => {
          this.translate = res.data;
          this.visibleKey = i
          // this.visibles[i] = !this.visibles[i];
          this.viLock = false;
      });
    },
    addWord() {
      addWord({
        prototype_word: this.translate.prototype_word,
        select_word: this.translate.select_word,
        question_id: this.detail.id,
        is_diff: "0",
      }).then((res) => {
        if (res.code === SUCCESS_CODE) {
          this.$message.success("添加生词成功");
        }
      });
    },
    translateVoice() {
      this.audio.src = this.translate.project_voice;
      this.audio.play();
    },
    translateDetail() {
      this.setTranslateModal({
        visible: true,
        word: this.translate.select_word,
      });
      document.getElementById("app").click();
    },
    selectWords(e, word) {
      console.log(e, word);
      word = this.replaceText(word);
      if (this.diffWords.has(word)) {
        if ($(e.srcElement).hasClass("diff_word_select")) {
          console.log($(e.srcElement));
          $(e.srcElement).removeClass("diff_word_select");
          this.diffWords.delete(word);
        } else {
          message.error("不可以添加重复的词");
          return;
        }
      } else {
        if (this.diffWords.size === 10) {
          message.error("最多可选10单词");
          return;
        }
        this.diffWords.add(word);
        $(e.srcElement).addClass("diff_word_select");
      }
    },
    subNewsWords() {
      if (!this.diffWords.size) {
        this.$message.error("请先选择单词~");
        return
      }
      addReadDiffWord({
        select_word: [...this.diffWords].toString(),
        question_id: this.detail.id,
        is_diff: "0",
      }).then((res) => {
        if (res.code === SUCCESS_CODE) {
          this.$message.success("添加生词成功");
          $(".js_diff_word").removeClass("diff_word_select");
          this.diffWords.clear();
        } else {
          this.$message.error("添加失败");
        }
      });
    },
    startClickHandle() {
      // 开始答题  生词隐藏
      this.isStart = true;
      this.isSelectWords = false;
      this.subTimer = setInterval(() => {
        this.readTime++;
        if (this.readTime >= 15 * 60) {
          clearInterval(this.subTimer)
        }
      }, 1000);
    },
    radioClick (index, word) {
      console.log(index, word)
      $('.blank').attr("style", "");
      $('.blank-val').eq(index).text('. ' + word.toString().replace(/,/g, ''))
      .parent('.blank').css({
        "background-color": "#27BFA3",
        color: "#fff",
      });
    },
    blankClick(e) {
      let el = $(e.srcElement).hasClass('blank') ? $(e.srcElement) : $(e.srcElement).parent('.blank');
      let index = $('.blank').index(el);
      this.scrollTitleClick(index);
      $('.blank').attr("style", "");
      el.css({
        "background-color": "#27BFA3",
        color: "#fff",
      });
    },

    subAnswer() {
      let rightNum = 0,
      errNum = 0;
      for (let i = 0; i < this.subjects.length; i++) {
        if (+this.subjects[i].answer === +this.subjects[i].right_option) {
          rightNum += 1;
        } else {
          errNum += 1;
        }
      }
      handUpQuestion({
        question_id: this.detail.id,
        question_type: "6",
        select_option: this.subjects.map((v) => v.answer).toString(),
        right_num: rightNum + '',
        err_num: errNum + '',
        score: parseInt((rightNum / this.subjects.length) * 100) + '',
      }).then((res) => {
        if (res.code === SUCCESS_CODE) {
          this.setReadDetail({})
          this.setReadReport({})
          this.$router.replace({
            path: "/super-read/report",
            query: { id: this.detail.id },
          });
        } else {
          this.$message.error(res.info);
        }
      });
    },
    goReport() {
      this.$router.push({
        path: "/super-read/report",
        query: { id: this.detail.id },
      });
    },
    scrollTitleClick(i) {
      this.stuSelectIndex = i
      let el = $(".sub-title").eq(i);
      // 点击滚动到顶部 滚动高 - 距离高 - 顶部固定高
      clearTimeout(this.scrollTimer)
      // window[`bs:event:scroll:close`] = true
      let height = $("#selectSection").scrollTop() + el.position().top - 80
      $("#selectSection").animate({
        scrollTop: height
      }, 500);
      // this.scrollTimer = setTimeout(() => {
      //   window[`bs:event:scroll:close`] = false
      // }, 2000)
      $('.article-content .blank').attr("style", "");
      $('.article-content .blank').eq(i).css({
        "background-color": "#27BFA3",
        color: "#fff",
      })
    },
    goList() {
      this.$yxpConfirm({
        msg: "是否退出",
      })
        .then(() => {
          this.$router.push({
            path: '/super-read/check-point',
			query: {type: this.$route.query.type,isnew:this.isnew,parent_id:this.parent_id,id:this.package_id,title:this.title}
          })
        })
        .catch(() => {});
    },
    scrollRmPop() {
      if (!window[`bs:event:scroll:close`]) {
          $(".ant-popover").empty();
          $('.ant-popover-open').removeClass('ant-popover-open')
      }
    },
  },
  created() {
    this.initList();
	this.isnew = this.$route.query.isnew;
	this.parent_id = this.$route.query.parent_id;
	this.package_id = this.$route.query.package_id;
	this.title = this.$route.query.title;
    // document.body.addEventListener("click", this.outPopClick);
    document.addEventListener('scroll', this.bodyClick, true)
  },
  beforeDestroy() {
    clearInterval(this.subTimer);
    this.$refs.timetips.stopTimer();
    this.$refs.timetips.stopEndTimer();
    if (this.audio) {
      this.audio.pause()
    }
    // document.body.removeEventListener("click", this.outPopClick);
    document.removeEventListener("scroll", this.bodyClick, true);
  },
  mounted() {
    this.audio = document.getElementById("reverse-audio");
  },
};
</script>
<style lang="less" scope>
/* @import url(); 引入公共css类 */
@import url("./index.less");
</style>
